const cloud = require("@cloudbase/node-sdk");

const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV,
});

var db = app.database();
const _ = db.command
const $ = db.command.aggregate
const ZXNeed = db.collection('ZX-Need')

const nowDate = db.serverDate()

// 获取openId云函数入口函数
exports.main = async (event, context,token) => {

    const api = event.api

    if(api=='api-need-add'){

        event.data.createTime = nowDate;
        event.data.zanUserList = []
        const res = await ZXNeed.add(event.data)
        return res

    }

    // 取消置顶
    if(api=='api-need-update-clear-top'){
        const _id = event.data._id
        return await ZXNeed.doc(_id).update({
            topNumber: 0,
        })
    }

    // 更新
    if(api=='api-need-update'){

        const type = event.data.type
        const _id = event.data._id
        const status = event.data.status

        if(type=='top'){
            const res =  await ZXNeed.doc(_id).update({
                topNumber: _.inc(1),
            })
            return res
        }else if(type=='zan'){
            let params = {}
            params.zanUserList = _.addToSet(token)
            params.zanNumber =  _.inc(1)
            const res =  await ZXNeed.doc(_id).update(params)
            return res
        }else if(type=='del'){
            const res =  await ZXNeed.doc(_id).update({
                status: status,
            })
            return res
        }
        
    }

    // 查询
    if(api=='api-need-list'){
        const res = await db
        .collection('ZX-Need')
        .aggregate()
        .match({
            status: 1,
        })
        .sort({
            topNumber: -1,
            zanNumber: -1,
            hotNumber: -1,
            createTime: -1,
        })
        .lookup({
            from: 'ZX-User',
            localField: 'userId',
            foreignField: '_id',
            as: 'userList'
        })
        .project({
            isZan: $.in([token, '$zanUserList']),
            contant: 1,
            createTime: 1,
            hotNumber: 1,
            status: 1,
            topNumber: 1,
            type: 1,
            userId: 1,
            zanNumber: 1,
            userList: 1,
        })
        .skip((event.data.pageIndex - 1) * event.data.pageSize)
        .limit(event.data.pageSize)
        .end()
        const list = res.data

        const total = await db
        .collection('ZX-Need')
        .aggregate()
        .match({
            status: 1,
        })
        .sort({
            topNumber: -1,
            zanNumber: -1,
            hotNumber: -1,
        })
        .count('total')
        .end()

        var tatalCount = 0
        if(total.data&&total.data.length>0){
            tatalCount = total.data[0].total
        }

        return {
            list: list,
            total: tatalCount
        }
    }

    
    
};